﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JieBooLaw.WebAdmin
{
    using Ext.Net;
    using Ext.Net.Utilities;
    using ListView = Ext.Net.ListView;
    using System.Collections.Generic;
    using JieBooLaw.Domain;
    using JieBooLaw.Service;

    public partial class RoleManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (X.IsAjaxRequest)
            {
                //We do not need to DataBind on an DirectEvent
                return;
            }

            //Build first level
            this.BuildLevel(0, "r0", "g0");
        }

        [DirectMethod]
        public void BuildLevel(int level, string recId, string gridId)
        {
            var storeId = "L".ConcatWith(level, "_", recId, "_Store");
            var newGridId = "L".ConcatWith(level, "_", recId, "_Grid");

            // build store
            var store = new Store { ID = storeId };
            var reader = new JsonReader { IDProperty = "ID" };
            reader.Fields.Add("RoleID", "PRoleID", "Level", "RoleCode", "RoleName", "Description", "Active");
            reader.Fields.Add(new RecordField
            {
                Name = "Level",
                Convert = { Handler = "return ".ConcatWith(level, ";"), }
            });
            store.Reader.Add(reader);
            store.CustomConfig.Add(new ConfigItem("level", level.ToString(), ParameterMode.Raw));

            // bind store
            var data = GetRoleByLevel(level);

            //build grid
            var grid = new GridPanel
            {
                ID = newGridId,
                Store = { store },
                AutoHeight = true,
                HideHeaders = level != 0
            };

            //build columns
            grid.ColumnModel.Columns.Add(new Column { DataIndex = "RoleCode", Header = "角色代码" });
            grid.ColumnModel.Columns.Add(new Column { DataIndex = "RoleName", Header = "角色名称" });
            grid.ColumnModel.Columns.Add(new Column { DataIndex = "Description", Header = "描述" });
            grid.ColumnModel.ID = newGridId + "_CM";

            // build view
            var view = new Ext.Net.GridView
            {
                ID = newGridId + "_View",
                ForceFit = true
            };
            grid.View.Add(view);

            // build selection model
            var sm = new RowSelectionModel { ID = newGridId + "_SM" };
            grid.SelectionModel.Add(sm);

            // add expander for all levels except last (last level is 5)
            if (level < 5)
            {
                view.Listeners.BeforeRefresh.Fn = "clean";
                var re = new RowExpander
                {
                    ID = newGridId + "_RE",
                    EnableCaching = true,
                    Template = { ID = newGridId + "_TPL", Html = "<div id=\"row_{ID}\" style=\"background-color:white;\"></div>" }
                };

                re.Listeners.BeforeExpand.Fn = "loadLevel";

                grid.Plugins.Add(re);
            }

            store.DataSource = data;
            store.DataBind();

            if (level == 0)
            {
                grid.Title = "角色管理";
                grid.AutoWidth = true;
                grid.AutoHeight = true;
                this.Form.Controls.Add(grid);

                grid.Plugins.Add(new PanelResizer());
            }
            else
            {
                var renderEl = "row_" + recId;
                X.Get(renderEl).SwallowEvent(new string[] { "click", "mousedown", "mouseup", "dblclick" }, true);

                this.RemoveFromCache(newGridId, gridId);
                grid.Render(renderEl, RenderMode.RenderTo);
                this.AddToCache(newGridId, gridId);
            }
        }

        private void RemoveFromCache(string id, string parentId)
        {
            this.ResourceManager1.AddScript("removeFromCache({0}, {1});", JSON.Serialize(id), JSON.Serialize(parentId));
        }

        private void AddToCache(string id, string parentId)
        {
            this.ResourceManager1.AddScript("addToCache({0}, {1});", JSON.Serialize(id), JSON.Serialize(parentId));
        }

        private List<TSys_Role> GetRoleByLevel(int level)
        {
            TSys_RoleSvc svc = new TSys_RoleSvc();
            List<TSys_Role> list = svc.GetAllList().Where(w => w.Level == level).ToList();

            return list;
        }

    }
}
